<?php

namespace App\Jobs;

use App\Models\Common\Common;
use App\Models\Tools\Data;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreApplyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $eo_id;

    /**
     * Create a new job instance.
     *
     * @param int $eo_id
     * @return void
     */
    public function __construct($eo_id)
    {
        $this->eo_id = $eo_id;
    }

    /**
     * Execute the job.
     * 结束订单发单过程
     *
     * @return void
     */
    public function handle()
    {
        try{
            DB::beginTransaction();
            // 查询订单状态（写锁）
            $order = DB::table('explore_order')
                ->where('eo_id','=',$this->eo_id)
                ->lockForUpdate()
                ->first();
            $order = json_decode(json_encode($order),true);
            // 查询当前账户当前渠道的探店剩余数量及使用状态（写锁）
            $remaining = DB::table('explore_remaining')
                ->where('we_id','=',$order['we_id'])
                ->where('channel_id','=',$order['channel_id'])
                ->lockForUpdate()
                ->first();
            $remaining = json_decode(json_encode($remaining), true);

            // 如果仍在发单阶段，停止发单并给一个对应的状态(如果不在发单状态直接结束)
            if($order['status'] === Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING){
                if($order['distribution_num']){ // 部分分发完成
                    $status = Data::DATA_DB_EXPLORE_ORDER_STATUS_PARTIAL_SUCCESS;
                    $action = Data::DATA_DB_EXPLORE_ORDER_ACTION_PARTIAL_SUCCESS;
                } else { // 无人抢单，分发超时
                    $status = Data::DATA_DB_EXPLORE_ORDER_STATUS_FAILED;
                    $action = Data::DATA_DB_EXPLORE_ORDER_ACTION_FAILED;
                }
                // 修改订单状态
                DB::table('explore_order')
                    ->where('eo_id','=',$this->eo_id)
                    ->update(['status' => $status]);
                // 记录日志
                DB::table('explore_order_log')
                    ->insert(['eo_id'=>$this->eo_id,'action'=>$action]);
                // 剩余未使用的单量退回到账户:正在使用的次数减少,可用单量增加（减少和增加的数量为剩余未派发的单量）
                DB::table('explore_remaining')->where('r_id','=',$remaining['r_id'])->update([
                    'remaining_times' => $remaining['remaining_times'] + $order['remaining_num'],
                    'in_use_times' => $remaining['in_use_times'] - $order['remaining_num'],
                ]);
                // 记录剩余单量日志
                DB::table('explore_remaining_log')->insert([
                    'r_id'=>$remaining['r_id'],
                    'action'=>Data::DATA_DB_EXPLORE_REMAINING_LOG_TYPE_DISPATCH,
                    'action_num'=>$order['remaining_num'],
                    'rest_num'=> $remaining['remaining_times'] + $order['remaining_num'],
                    'in_use_num'=> $remaining['in_use_times'] - $order['remaining_num'],
                ]);

                // 发送微信推送给商家
                try{
                    // 发送微信推送给商家，通知发单过期
                    $data = [
                        'first' => '您发起的探店邀请未被接单，请查看',
                        'keyword1' => date('Y-m-d H:i:s'),
                        'keyword2' => '已超时',
                        'remark' => '您的探店剩余次数已返还，您可以重新发单。',
                    ];
                    //发送通知
                    $openid = DB::table('lottery_users')->where('we_id','=',$order['we_id'])->value('openid');
                    Common::sendLaifeiMessage($openid,'order_timeout',$data,'/history?tab=1');
                }catch (\Exception $e){
                    Log::emergency(ExploreApplyJob::class,['eo_id'=>$this->eo_id,'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                }

            }
            DB::commit();

        }catch (\Exception $e){
            Log::emergency(ExploreApplyJob::class,['eo_id'=>$this->eo_id,'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return; // 异常状态提前结束
        }


    }
}
